import { Toast } from "vant";
import { ref, watch, Ref, reactive, toRefs, watchEffect } from "vue";

interface PropsInterface {
	getData: (any) => void;
	option: {
		defaultFilters?: {
			[propsName: string]: any;
		};
		pageParamsRename?: {
			current: string;
			size: string;
		};
		manual: boolean;
	};
}

const SIZE = 10;

export default function (props: PropsInterface) {
	const listRes = reactive({
		list: [],
		total: 0,
		isLastPage: false,
		loadingStatus: "more",
	});

	const params = {
		current: 1,
		size: SIZE,
		default: {},
	};

	const changeListView = async () => {
		listRes.loadingStatus = "loading";
		Toast.loading({
			duration: 0,
		});
		const queryParams = { ...params, ...params.default };
		delete queryParams.default;

		/* 处理分页参数格式 */
		if (props.option.pageParamsRename) {
			const { current, size } = props.option.pageParamsRename;
			queryParams[current] = queryParams.current;
			queryParams[size] = queryParams.size;
			delete queryParams.current;
			delete queryParams.size;
		}
		const rs = await props.getData(queryParams);
		Toast.clear();
		if (rs.ok) {
			const _current = params.default?.current || params.current;
			const _size = params.default?.size || params.size;
			const data = rs.data;
			listRes.isLastPage = _current * _size >= data.total;
			listRes.loadingStatus =
				_current * _size >= data.total ? "noMore" : "more";
			listRes.total = data.total;
			listRes.list = [...listRes.list, ...(data.records || [])];
		}
	};

	const getMore = () => {
		if (!listRes.isLastPage) {
			params.current = params.current + 1;
			changeListView();
		}
	};

	const start = (val) => {
		params.current = 1;
		params.size = SIZE;
		params.default = { ...params.default, ...val };
		listRes.isLastPage = false;
		listRes.total = 0;
		listRes.list = [];
		changeListView();
	};

	watchEffect(() => {
		const { option } = props;
		params.default = { ...(option?.defaultFilters || {}) };
		if (!option.manual) {
			changeListView();
		}
	});

	return {
		listRes,
		start,
		getMore,
	};
}
